package com.tanhua.dubbo.server.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private HuanXinConfig huanXinConfig;

    private static final String REDIS_KEY = "HX_TOKEN";

    /**
     * 获取token  (环信中的token)
     *
     * @return
     */
    public String getToken(){
        // 先从redis中获取, 如果没有再去环信接口获取
        String token = redisTemplate.opsForValue().get(REDIS_KEY);
        if (StrUtil.isNotEmpty(token)){
            return token;
        }
        // 访问环信接口获取token
        return refreshToken();
    }

    /**
     * 刷新token，请求环信接口，将token存储到redis中
     *
     * @return
     */
    public String refreshToken() {
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/" + "token";
        Map<String,Object> map = new HashMap<>();
        map.put("grant_type", "client_credentials");
        map.put("client_id", huanXinConfig.getClientId());
        map.put("client_secret", huanXinConfig.getClientSecret());

        HttpResponse response = HttpRequest.post(targetUrl).body(JSONUtil.toJsonStr(map)).timeout(20000).execute();
        if (!response.isOk()){
            log.error("刷新token失败!");
            return null;
        }
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String token = jsonObject.getStr("access_token");
        if (StrUtil.isNotEmpty(token)){
            //将token数据缓存到redis中, 缓存时间有expires_in决定
            //提前 1 小时失效
            Long timeout = jsonObject.getLong("expires_in") - 3600;
            redisTemplate.opsForValue().set(REDIS_KEY,token,timeout, TimeUnit.SECONDS);
            return token;
        }
        return null;
    }
}
